"""
license resource
"""
from __future__ import absolute_import, print_function, division
from datetime import timedelta, date

import json
import random
import cherrypy


class License(object):

    QuantityC, DateC = range(0, 2)

    charBase = list(set(map(chr, list(range(ord('A'), ord('Z'))) +
                            list(range(ord('0'), ord('9'))))) -
                    set(['I','O','0','1']))

    def __init__(self, key, ctype, amount):
        self.key = key
        self.ctype = ctype
        self.amount = amount
        self.redeemed = False

    def to_json(self):
        j = {}
        j['key'] = self.key
        j['amount'] = self.amount

        if self.ctype == License.DateC:
            j['type'] = 'period'
        else:
            j['type'] = 'amount'

        return json.dumps(j)

    @staticmethod
    def random_license():
        key = "".join([random.choice(License.charBase) for i in range(0, 20)])
        ctype =  random.choice([License.QuantityC, License.DateC])
        amount = random.randint(1, 100)

        return License(key, ctype, amount)


class LicenseManager(object):

    exposed = True

    def __init__(self):
        #hardcoded test quantityc license for testing purpose
        self.test_quantityc_license = License(key="RKNP3D6XCUTXNY2HE8SH",
                                             ctype=License.QuantityC, amount=66)
        #hardcoded test datec license for testing purpose
        self.test_datec_license = License(key="MQDYE8LBHVRECQMASBGM",
                                          ctype=License.DateC, amount=500)


    def reactivate_test_licenses(self):
        self.test_datec_license.redeemed = False
        self.test_quantityc_license.redeemed = False

    def find_license(self, key):
        if (self.test_datec_license.key == key and
            not self.test_datec_license.redeemed):

            self.test_datec_license.redeemed = True
            return self.test_datec_license
        elif (self.test_quantityc_license.key == key and
              not self.test_quantityc_license.redeemed):

            self.test_quantityc_license.redeemed = True
            return self.test_quantityc_license
        else:
            return None

    def mgmt_handler(self, method, params):
        if method == 'reset':
            self.reactivate_test_licenses()
            cherrypy.log("test-licenses have been reactivated")
        else:
            cherrypy.log("method %s is not supported" % (method,))

    def DELETE(self, key, system, user, *args, **kw):

        license = self.find_license(key)

        if license:
            return license.to_json()
        else:
            #raise HTTPError
            raise cherrypy.HTTPError(403, "Your license is not valid")

    def POST(self):
        cl = cherrypy.request.headers['Content-Length']
        rawbody = cherrypy.request.body.read(int(cl))
        request = json.loads(rawbody)

        self.mgmt_handler(request['method'], request['params'])
        return "POST received"
